<template>
  <div>
    <el-dialog
      :title="mode === 'add' ? '新增角色' : '编辑角色'"
      :visible="isShow"
      width="400"
      @close="closeEvent"
    >
      <el-form :model="form" ref="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model.trim="form.name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model.trim="form.description"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="footer">
          <el-button @click="closeEvent">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { sysRolePost, sysRolePut } from '@/api/setting'
export default {
  name: 'DialogItem',
  props: {
    isShow: {
      type: Boolean,
      default: false
    },
    list: {
      type: Array,
      default: () => []
    }
  },
  model: {
    prop: 'isShow' 
  },
  data () {
    return {
      mode: 'add',
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              let result = ''
              if (this.mode === 'add') {
                result = this.list.some(item => {
                  return item.name === value
                })
              } else {
                result = this.list.some(item => {
                  return item.name === value && this.form.id !== item.id
                })
              }
              result ? callback(new Error('请不要输入重复的名字')) : callback()
            }
          }
        ],
        description: [{ required: true, message: '必填', trigger: 'change' }]
      }
    }
  },
  methods: {
    // 新增/编辑角色
    submit () {
      this.$refs.form.validate(async result => {
        if (result) {
          // 新增
          if (this.mode === 'add') {
            await sysRolePost(this.form)
            this.$emit('pageChange', 1)
          } else {
            // 编辑
            await sysRolePut(this.form)
            this.$emit('getData')
          }
          this.$message.success(this.mode === 'add' ? '新增成功' : '编辑成功')
          this.closeEvent()
        }
      })
    },
    closeEvent () {
      this.$emit('update:isShow', false)
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  text-align: center;
}
</style>
